package org.colcon.web.client.ui;

import org.colcon.web.client.Collective_Congress;
import org.colcon.web.client.ui.panel.LoginPanel;
import org.colcon.web.client.ui.panel.UserPanel;
import org.colcon.web.model.Item;
import org.colcon.web.model.Model;
import org.colcon.web.model.framework.IContainer;
import org.colcon.web.model.framework.IUser;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;

public class LinkPanel extends ClickablePanel 
{
	private String path;
	
	public LinkPanel(Collective_Congress client, String path) 
	{
		this(client, "link", path);
	}
	
	public LinkPanel(Collective_Congress client, String style, String path) 
	{
		this(client, style, Model.parseId(path), path);
	}
	
	public LinkPanel(Collective_Congress client, String style, String text, String path) 
	{
		super(client, style, text);
		
		this.path = path;
	}

	public String getPath()
	{
		return path;
	}
	
	public void click() 
	{
		getBodyPanel().clear();
		
		if(!getClient().loggedIn())
		{
			getBodyPanel().add(new LoginPanel(getClient()));
			return;
		}
		
		getBodyPanel().add(new Label("Loading..."));
		
		getService().get(path, new AsyncCallback<Item>()
		{
			public void onFailure(Throwable caught)
			{
				getBodyPanel().clear();
				getBodyPanel().add(new Label("failed to get item " + path));
			}
			
			public void onSuccess(Item item)
			{
				getBodyPanel().clear();
				
				if(item != null)
				{
					ItemPanel panel;
					
					if(item.isContainer())
						panel = new ContainerPanel(getClient(), (IContainer) item);
					else if(item instanceof IUser)
						panel = new UserPanel(getClient(), (IUser) item);
					else
						panel = new ItemPanel(getClient(), item);
					
					getBodyPanel().add(panel);
				}
				else
				{
					getBodyPanel().add(new Label("failed to get item " + item));
				}
			}
		});
	}
}
